import TopSearch from "@/components/TopSearch";
import { UserAddOutlined } from "@ant-design/icons";
import { useState, useEffect } from "react";
import Card from "@/components/Card";
import AddUserCommponent from "../components/AddUserCommponent";
import { getFriendList, getFriendlist } from "@/api/xhr/friends";
import { useSelector } from "react-redux";

type Typefriendslist = {
  id: number;
  name: string;
  avatar: string;
};
const controls = {
  isshowtime: false, //是否显示时间
  isshowmessage: false, //是否显示消息
  isnav: true
};
const FriendsList = ({ onContext }) => {
  const userinfo = useSelector((state: any) => state.user.userinfo);
  const [searchValue, setsearchValue] = useState("");
  const [showAddUser, setshowAddUser] = useState<boolean>(false);
  const [friendslist, setfriendslist] = useState<Typefriendslist[]>([]);
  async function friendList() {
    const friendslistres = await getFriendList({ userId: userinfo.id });
    setfriendslist(
      friendslistres.data.map(item => {
        return {
          id: item.id,
          name: item.commendName ? item.commendName : item.userName,
          avatar: item.userAvatar
        };
      })
    );
  }
  useEffect(() => {
    friendList();
    onContext(friendList);
  }, []);
  function toAddUser() {
    setshowAddUser(true);
  }
  async function searchFunc(searchvalue: string) {
    if (searchvalue) {
      const res = await getFriendlist({ userId: userinfo.id, searchvalue });
      if (res.statusCode == 200) {
        setfriendslist(
          res.data.map(item => {
            return {
              id: item.id,
              name: item.commendName ? item.commendName : item.userName,
              avatar: item.userAvatar
            };
          })
        );
      }
    } else {
      friendList();
    }
  }
  return (
    <>
      <TopSearch
        value={searchValue}
        setvalue={setsearchValue}
        searchFunc={searchFunc}
      >
        <div className="h-full w-full" onClick={toAddUser}>
          <UserAddOutlined />
        </div>
      </TopSearch>
      <div className="overflow-y-scroll scrollbar-hide h-full w-full scrollbar select-none cursor-auto ">
        {friendslist.length ? (
          friendslist.map(item => {
            return <Card key={item.id} item={item} controls={controls}></Card>;
          })
        ) : (
          <div className="text-sm text-gray-400">暂无数据</div>
        )}
      </div>
      <AddUserCommponent
        show={showAddUser}
        setshow={setshowAddUser}
      ></AddUserCommponent>
    </>
  );
};

export default FriendsList;
